package com.superhero.common.handle;

import com.alibaba.fastjson.JSONObject;
import com.superhero.common.pojo.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;



@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 参数验证错误返回code
     */
    public static final int PARAMETER_ERROR_CODE = 400;

    /**
     * 处理校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JSONObject handleConstraintViolationException(ConstraintViolationException e) {
        // 处理验证异常
        Set<ConstraintViolation<?>> validations = e.getConstraintViolations();
        if (validations != null) {
            StringBuilder buf = new StringBuilder();
            validations.forEach(validation -> buf.append(validation.getMessage()));
            return toErrorJsonResponse(PARAMETER_ERROR_CODE, buf.toString(), e);
        } else {
            return toErrorJsonResponse(PARAMETER_ERROR_CODE, e.getMessage(), e);
        }
    }

    /**
     * 处理校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    public JSONObject handleViolationException(ValidationException e) {
        Throwable rootCause = e.getCause();
        if (rootCause instanceof InvocationTargetException) {
            Throwable target = ((InvocationTargetException) rootCause).getTargetException();
            return toErrorJsonResponse(PARAMETER_ERROR_CODE, target.getMessage(), target);
        } else {
            return toErrorJsonResponse(PARAMETER_ERROR_CODE, e.getMessage(), e);
        }
    }

    /**
     * web方法参数错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public JSONObject handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder buf = new StringBuilder();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            buf.append(fieldError.getDefaultMessage()).append(" ");
        });
        bindingResult.getGlobalErrors().forEach(globalError -> {
            buf.append("globalErrorCode=").append(globalError.getCode()).append("\n");
        });
        return toErrorJsonResponse(PARAMETER_ERROR_CODE, buf.toString(), e);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JSONObject handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder buf = new StringBuilder();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            buf.append(fieldError.getDefaultMessage()).append(" ");
        });
        bindingResult.getGlobalErrors().forEach(globalError -> {
            buf.append("globalErrorCode=").append(globalError.getCode()).append("\n");
        });
        return toErrorJsonResponse(PARAMETER_ERROR_CODE, buf.toString(), e);
    }

    /**
     * 处理所有其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JSONObject handleAllException(Exception e) {
        return toErrorJsonResponse(500, e.getMessage(), e);
    }

    private JSONObject toErrorJsonResponse(int code, String errorMsg, Throwable e) {
        if (StringUtils.isEmpty(errorMsg)) {
            errorMsg = "系统异常";
        }
        int resultCode = code;
        if (e instanceof IllegalArgumentException || e instanceof ConstraintViolationException) {
            resultCode = PARAMETER_ERROR_CODE;
        } else if (code == -1) {
            resultCode = 500;
        }
        log.warn("GlobalExceptionHandler | err={}", errorMsg, e);
        return ApiResult.error(resultCode, errorMsg).toJSON();
    }
}
